import { createStore } from "vuex"
import routerMode, { metaMode, asyncRoutes } from "@/router/index"


interface appState {
    token: string | null,
    isLoading: boolean,
    powerRoutes: Array<any>
}
function hasPemission(role, route): boolean {
    console.log('route?.meta', route?.meta)
    if (route.meta?.role) {
        console.log('route?.meta',route?.meta)
        return route.meta.role.includes(role)
    } else {
        return true
    }
}

function filterAsycRouteFN(role, routes) {
    const result: Array<any> = []
    console.log('filterAsycRouteFN-routes',routes)
    routes.forEach((route) => {
        console.log('循环泵')
        const tmp = { ...route }
        if (hasPemission(role, tmp)) {
            if (tmp.children) {
                
                tmp.children = filterAsycRouteFN(role,tmp.children)
            }
            result.push(tmp)
        }
    })
    return result
}


const store = createStore<appState>({
    state: {
        token: "",
        isLoading: false,
        powerRoutes: []
    },
    mutations: {
        set_loading(state, status: boolean) {
            state.isLoading = status
        },
        login(state, token) {
            state.token = token
        },
        logout(state) {
            state.token = ''
        },
        set_router(state, powerRoutes) {
            state.powerRoutes = powerRoutes
        }
    },
    getters: {
        getPowerRoutes : (state)=>{ return state.powerRoutes }
    },
    actions: {
         generateRoutes({ commit }, role) {
             console.log('当前角色', role)
            return new Promise((resolve) => {
                // 存取路由
                let route:Array<any> = []
                // 如果是admin角色（最高权限），则返回全部异步路由，不做拦截
                if (role == 'admin') {
                    route = asyncRoutes || []
                } else {
                    route = filterAsycRouteFN(role, asyncRoutes)
                }
                commit('set_router', route)
                resolve(route)
            })

        }
    }
})

export default store